﻿using System;
using System.Collections.Generic;

namespace Alvin.Common.Utils
{
    public static class SearchPathUtil
    {
        /// <summary>
        /// 生成searchPath值
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static String ToSearchPath(int id)
        {
            return ToSearchPath(id,null);
        }

        /// <summary>
        /// 生成searchPath值
        /// </summary>
        /// <param name="id"></param>
        /// <param name="parentSearchPath">上级SearchPath值</param>
        /// <returns></returns>
        public static String ToSearchPath(int id,String parentSearchPath)
        {
            var sb = new System.Text.StringBuilder();
            if (String.IsNullOrWhiteSpace(parentSearchPath))
            {
                sb.Append("[").Append(id).Append("]");
            }
            else
            {
                sb.Append(parentSearchPath).Append(".[").Append(id).Append("]");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 将SearchPath值转成数组
        /// </summary>
        /// <param name="searchPath"></param>
        /// <returns></returns>
        public static IList<int> ParseToIdList(String searchPath)
        {
            if (String.IsNullOrWhiteSpace(searchPath))
            {
                throw new Exception(String.Format("非法的SearchPath值：{0}", searchPath));
            }
            searchPath = searchPath.Replace("[", "").Replace("]", "");
            var arr = searchPath.Split('.');
            var inarr = new List<int>(arr.Length);
            for (int i = 0, length = arr.Length; i < length; i++)
            {
                inarr[i] = Convert.ToInt32(arr[i]);
            }
            return inarr;
        }
    }
}
